﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.Common;
using OBUCare.Core.DataAccess;
using OBUCare.Core.BL;
using OBUCare.Web.Infrastructure;
using Telerik.Web.Mvc;
using System.Collections.Specialized;
using OBUCare.Web.Models;

namespace OBUCare.Web.Controllers
{
    public class PartsReportController : Controller
    {
        ConfigMgr configMrg;
        OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();

        //
        // GET: /PartsReport/

        public ActionResult Index()
        {
            return View("Transaction");
        }

        #region 元器件划拨明细

        public ActionResult Transaction()
        {
            return View();
        }

        #endregion


        #region 入库

        public ActionResult StockIn()
        {
            ViewBag.StockType =UIConstants.AllItems;
            IList<SelectListItem> list = new List<SelectListItem>();
            list = new ObuDropDownListHlper().GetInStockBy(UIConstants.AllItems, true, new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems));
            ViewBag.ListData = list;
            return View();
        }

        [GridAction]
        public ActionResult ListPartsStockIn(string sql, string searchSql)
        {
            var result = getPartsStockIn(sql, searchSql).ToList();
            var temp = new GridModel(result.OrderByDescending(m=>m.CREATED_DATE));
            return View(temp);
        }

        /// <summary>
        /// 根据sql返回查询后可冲正交接记录
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        private IEnumerable<View_PartsStockDetails> getPartsStockIn(string sql, string searchSql)
        {
            string tempSql = "";
            if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                tempSql = sql + " and " + searchSql;
            else
                tempSql = string.Format("{0} {1}", sql, searchSql);

            if (tempSql.Trim() == "")
                tempSql += " RECORD_DATE>='" + DateTime.Now.ToShortDateString() + "' and RECORD_DATE<'"+DateTime.Now.AddDays(1).ToShortDateString()+"'";

            

            var result = obuMgr.GetPartsStockIn(tempSql);

            return result;
        }

        [HttpPost]
        public JsonResult PartsStockInSearch(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string Supplier, string SpecName,
            string PartType, string StockType) //也可以用这种格式接收参数public ActionResult Search(FormCollection form)
        {
            try
            {
                var sql = obuMgr.GetSearhPartsStockInSql(FromCreatedDate, ToCreatedDate,
                    Supplier.ChangAllTextToNull(), SpecName.ChangAllTextToNull(), PartType.ChangAllTextToNull(), StockType.ChangAllTextToNull());

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }

        #endregion

        #region 销售

        public ActionResult Sale()
        {
            return View();
        }

        [GridAction]
        public ActionResult ListPartsSale(string sql, string searchSql)
        {
            var result = getPartsSale(sql, searchSql).ToList();
            var temp = new GridModel(result.OrderByDescending(r=>r.CREATED_DATE));
            return View(temp);
        }

        /// <summary>
        /// 根据sql返回查询后元器件销售记录
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        private IEnumerable<View_PARTS_SALE> getPartsSale(string sql, string searchSql)
        {
            //根据编号判断查询权限
            string whereAgentNo = Request["agentNO"] == null || Request["agentNO"].ToString() == "" ? "" : Request["agentNO"].ToString();
            string modelID = Request["menuNames"] == null || Request["menuNames"].ToString() == "" ? "" : Request["menuNames"].ToString();
           
            string tempSql = "";
            if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                tempSql = sql + " and " + searchSql;
            else
                tempSql = string.Format("{0} {1}", sql, searchSql);


            //如果最小权限为6 则增加操作员查询条件
            whereAgentNo = whereAgentNo == "" ? "" : " AND AGENT_NO='" + whereAgentNo + "'";
            OPERATOR operatorInfo = UIUtility.GetCurrentUser();
            string models = UIUtility.getOperatorByModule(operatorInfo, Convert.ToInt32(modelID));
            if (models == "6")
                whereAgentNo += " AND CREATED_BY='" + operatorInfo.OPERATOR_NO + "'";

            string normalSql = tempSql.Trim() == "" ?
            "  [REPORT_DATE]>='" + DateTime.Now.ToShortDateString() + "' AND [REPORT_DATE] <'" + DateTime.Now.AddDays(1).ToShortDateString() + "' " :
            "";//如果没有任何条件 则默认显示当天的所有信息

            var result = obuMgr.GetPartsSale(tempSql+normalSql+whereAgentNo);
            return result;
        }

        [HttpPost]
        public JsonResult PartsSaleSearch(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string PartType, 
            string Supplier, string SpecName, string AgentType, string Agent, string Operator, string ObuNo,
            string Amount) //也可以用这种格式接收参数public ActionResult Search(FormCollection form)
        {
            try
            {
                var sql = obuMgr.GetSearhPartsSaleSql(FromCreatedDate, ToCreatedDate, PartType.ChangAllTextToNull(), Supplier.ChangAllTextToNull(),
                    SpecName.ChangAllTextToNull(), AgentType.ChangAllTextToNull()
                    , Agent.ChangAllTextToNull(), Operator.ChangAllTextToNull(), ObuNo.ChangAllTextToNull().Trim(),Amount.ChangAllTextToNull().Trim());

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }

        #endregion

        /// <summary>
        /// 根据厂商获取已配置好的型号信息
        /// </summary>
        /// <param name="supplierID"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult getSpecs(string supplierID)
        {
            int ID = 0;
            if (supplierID == "全部")
                ID = 0;
            else
                ID = Convert.ToInt32(supplierID);
            var result = new ObuDropDownListHlper().GetPartsSpecs(null, ID, true);
            if (result.Count() == 0)
                result.Add(new SelectListItem() { Value = "0", Text = "无" });
            else
                result.Insert(0, new SelectListItem(){Value=UIConstants.AllItems,Text= UIConstants.AllItems});
             return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            obuMgr.Dispose();
            base.Dispose(disposing);
        }
    }
}
